import 'package:flutter/material.dart';
import 'package:get/get.dart';

class CommonFormItem extends StatelessWidget {
  final String label;
  final Widget Function(BuildContext context)? contentBuilder;

  final Widget? suffix;
  final String? suffixText;

  final String hintText;
  final ValueChanged? onChanged;
  final bool clearable;
  final value = "".obs;

  CommonFormItem({
    super.key,
    required this.label,
    this.contentBuilder,
    this.suffix,
    this.suffixText,
    this.hintText = "请输入",
    this.onChanged,
    this.clearable = false,
  });

  void _changeValue(String val) {
    value.value = val;
    if (onChanged != null) {
      onChanged!(val);
    }
  }

  @override
  Widget build(BuildContext context) {
    final controller = TextEditingController.fromValue(
      TextEditingValue(
        text: value.value ?? "",
        selection: TextSelection.fromPosition(
          TextPosition(
            affinity: TextAffinity.downstream,
            offset: value.value.length ?? 0,
          ),
        ),
      ),
    );
    return Obx(
      () => Container(
        decoration: BoxDecoration(
          border: Border(
            bottom: Divider.createBorderSide(context, width: 1),
          ),
        ),
        child: Row(
          children: [
            SizedBox(
              width: 100,
              child: Text(
                label,
                style: Get.theme.textTheme.labelMedium,
              ),
            ),
            contentBuilder != null
                ? contentBuilder!(context)
                : Expanded(
                    child: TextField(
                      controller: controller,
                      decoration: InputDecoration(
                        hintText: hintText,
                        border: InputBorder.none,
                        focusedBorder: InputBorder.none,
                        enabledBorder: InputBorder.none,
                        suffixIcon: Offstage(
                          offstage: !clearable || value.value.isEmpty,
                          child: IconButton(
                            onPressed: () {
                              controller.clear();
                              _changeValue("");
                            },
                            icon: const Icon(Icons.clear),
                          ),
                        ),
                      ),
                      onChanged: _changeValue,
                    ),
                  ),
            if (suffix != null) suffix!,
            if (suffix == null && suffixText != null) Text(suffixText!),
          ],
        ),
      ),
    );
  }
}
